using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace HBFramework
{
    public class StorageBehaviour_Normal : IStorageBehaviour
    {
        private const string filePath = "storage.json";
        private Dictionary<string, string> dataDict;
        private bool isDirty;

        public void Init()
        {
            var dataString = PresistentFileUtility.LoadFile(filePath, "");
            dataDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(dataString);
            dataDict ??= new Dictionary<string, string>();
            isDirty = false;
        }

        public void Update()
        {
            if (isDirty)
            {
                var json = JsonConvert.SerializeObject(dataDict);
                PresistentFileUtility.SaveFile(filePath, json);
                isDirty = false;
            }
        }

        public string GetDataString(string key)
        {
            return dataDict[key];
        }

        public void SetDataString(string key, string data)
        {
            if (dataDict.ContainsKey(key))
            {
                dataDict[key] = data;
            }
            else
            {
                dataDict.Add(key, data);
            }
        }

        public void ClearAll()
        {
            PresistentFileUtility.DeleteFile(filePath);
        }
    }
}